from urllib import error
from urllib import request
import json
import argparse

from util.json import json_file2obj

config = json_file2obj('config/config.json')


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--port", help="the port the of web server that you want to stop", type=int, default=config.web.port)
    a = parser.parse_args()

    url = "http://localhost:%s/stop/server?pwd={pwd}" % a.port
    url = url.format(pwd=request.quote(config.web.stop_password))

    try:
        response = request.urlopen(url)
        result = response.read()
        result = json.loads(result.decode())
    except error.URLError as e:
        result = {
            "result": False,
            "msg": "found URL error(%s)" % e
        }

    success = ("Success" if result["result"] else "Fail") + " to stop the server on port %d" % a.port
    print("%s!, %s" % (success, result["msg"]))
